// $URL: http://mingw-lib.googlecode.com/svn/trunk/local/box/yt_dump/xmlutil.cpp $
// $Rev: 502 $
// $Author: akio.miyoshi $
// $Date:: 2010-11-11 11:21:01 +0000#$

#include "xmlutil.h"

#include <QtCore>
#include <QtGui>
#include <QtXml>

static void s_setDesktopFile(QFile &file, QString name)
{
    QString dirPath =
            QDesktopServices::storageLocation(
                    QDesktopServices::DesktopLocation);
    QDir dir(dirPath);
    QString filePath = dir.filePath(name);
    file.setFileName(filePath);
}

void s_saveDesktopFile(QString name, QByteArray bytes)
{
    QFile file;
    s_setDesktopFile(file, name);
    qDebug() << file.fileName();
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    file.write(bytes);
}

void XmlUtil::writeXmlContent(QDomDocument &domDocument, QIODevice *device)
{
    QTextStream v_textout(device);
    const int IndentSize = 4;
    domDocument.save(v_textout, IndentSize);
}

QByteArray XmlUtil::formatXml(QByteArray &rawXml)
{
    QDomDocument domDocument;
    if (!XmlUtil::setXmlContent(domDocument, rawXml))
    {
        return rawXml;
    }
    QBuffer v_out;
    v_out.open(QIODevice::WriteOnly);
    QTextStream v_textout(&v_out);
    XmlUtil::writeXmlContent(domDocument, &v_out);
    v_out.close();
    return v_out.buffer();
}

bool XmlUtil::setXmlContent(QDomDocument &domDocument, QByteArray &rawXml)
{
    QBuffer v_in;
    v_in.setBuffer(&rawXml);
    QString v_errorStr;
    int v_errorLine;
    int v_errorColumn;
    if (!domDocument.setContent(
            &v_in,
            true,
            &v_errorStr,
            &v_errorLine,
            &v_errorColumn))
    {
        qDebug() << qApp->tr("Parse error at line %1, column %2:\n%3")
               .arg(v_errorLine)
               .arg(v_errorColumn)
               .arg(v_errorStr);
        qDebug() << "[rawXml]" << rawXml;
        return false;
    }
    return true;
}

void XmlUtil::backupXmlBody(QByteArray a_bytes, QString a_fileNameBody)
{
    if (a_fileNameBody=="") a_fileNameBody = "body";
    //s_saveDesktopFile(QString("%1.orig.txt").arg(a_fileNameBody), a_bytes);
    QByteArray v_formated = XmlUtil::formatXml(a_bytes);
    s_saveDesktopFile(QString("%1.txt").arg(a_fileNameBody), v_formated);
}
